import subprocess
from flask import Blueprint, jsonify, session
from exts import mail, db
from flask_mail import Message
from flask import request
import string
import random
from models import EmailCaptchaModel
from .forms import RegisterForm,LoginForm
from werkzeug.datastructures import MultiDict
from models import UserModel
from werkzeug.security import generate_password_hash, check_password_hash

bp = Blueprint("auth", __name__, url_prefix="/auth")

#这里是验证登录信息
@bp.route("/register", methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        data = request.get_json()   #这里前端返回的是json
        data_form = MultiDict(data)   #用MultiDict函数将json格式转化为request.from格式
        form = RegisterForm(data_form)
        if form.validate():
            email = form.email.data
            username = form.username.data
            password = form.password.data
            user = UserModel(email=email, username=username, password=generate_password_hash(password))
            db.session.add(user)
            db.session.commit()
            return "success"
        else :
            return "fail"


#这里是发送验证码
#如果没有指定，默认是GET请求
@bp.route("/captcha/email", methods=['POST'])
def get_email_captcha():
    email = request.args.get("email")
    source = string.digits * 4
    captcha = random.sample(source, 4)
    captcha = "".join(captcha)
    message = Message(subject="医学图像分割系统注册验证码", recipients=[email], body=f"您的验证码是:{captcha}")
    mail.send(message)
    #这里用数据库存储验证码
    email_captcha = EmailCaptchaModel(email=email, captcha=captcha)
    db.session.add(email_captcha)
    db.session.commit()
    return jsonify({
        "code": 200,
        "message" : "",
        "data" : None
    })

#登录页面逻辑的实现
@bp.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        data = request.get_json()
        data_form = MultiDict(data)
        form = LoginForm(data_form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            user = UserModel.query.filter_by(email=email).first()
            if not user:
                return "emailerror"
            if check_password_hash(user.password,password):
                # cookie:
                # cookie中不适合存储太多的数据，只适合存储少量的数据
                # cookie中一般用来存放登录授权的东西
                # flask中的session，是经过加密后存储再cookie中的
                session['user_id'] = user.id
                return "success"
            else :
                return "passworderror"
        else:
            print(form.errors)
            return "fail"

@bp.route('/upload',methods=['POST', 'GET']) # 方法要与前端一致
def upload():
    if request.method == "POST":
        file = request.files['file']
        file.save('3.nii.gz')
        return "success"
    else:
        subprocess.call(["python", "main.py"])

